import {request} from "../../api/request"

Page({
    data: {
        phoneNumber: '',
        verificationCode: '',
        counting: false,
        countDown: 60,
        agreed: false,
        from: ""
    },
    onLoad(query) {
        const from = query.from
        this.setData({from: from});
    },
    onPhoneInput(e) {
        this.setData({
            phoneNumber: e.detail.value
        });
    },

    onCodeInput(e) {
        this.setData({
            verificationCode: e.detail.value
        });
    },

    onAgreementChange(e) {
        this.setData({
            agreed: e.detail.value.length > 0
        });
    },

    sendCode() {
        const {phoneNumber} = this.data;
        if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
            wx.showToast({
                title: '请输入正确的手机号',
                icon: 'none'
            });
            return;
        }

        // 开始倒计时
        this.setData({
            counting: true,
            countDown: 60
        });

        const timer = setInterval(() => {
            if (this.data.countDown <= 1) {
                clearInterval(timer);
                this.setData({
                    counting: false
                });
            } else {
                this.setData({
                    countDown: this.data.countDown - 1
                });
            }
        }, 1000);


        request({
            url: `/user/getCaptcha?phone=${phoneNumber}`,
            method: 'GET',
        }).then(res => {
                if (res.data.code === 0) {
                    if (res.header['Set-Cookie']) {
                        let setCookies = res.header['Set-Cookie'].split(';');
                        setCookies = setCookies[0]
                        const cookies = wx.getStorageSync('Cookie') || {};

                        const [cookieName, cookieValue] = setCookies.split('=');
                        wx.setStorageSync('Cookie', {...cookies, [cookieName]: cookieValue});
                    }
                    wx.showToast({
                        title: '验证码已发送',
                        icon: 'success'
                    });
                } else {
                    wx.showToast({
                        title: '验证码发送失败',
                        icon: 'none'
                    });
                }
            }
        )
    },

    handlePhoneLogin() {
        const {phoneNumber, verificationCode, agreed} = this.data;

        if (!agreed) {
            wx.showToast({
                title: '请先同意用户协议',
                icon: 'none'
            });
            return;
        }

        if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
            wx.showToast({
                title: '请输入正确的手机号',
                icon: 'none'
            });
            return;
        }

        if (!/^[a-zA-Z0-9]{4}$/.test(verificationCode)) {
            wx.showToast({
                title: '请输入4位验证码',
                icon: 'none'
            });
            return;
        }

        const from = this.data.from;
        wx.login({
            success(res) {
                if (res.code) {
                    //发起网络请求
                    request({
                        url: '/user/login_wx',
                        method: 'POST',
                        data: {
                            code: res.code,
                            phone: phoneNumber,
                            captcha: verificationCode
                        }
                    }).then(res => {
                        // 如果响应头中包含 Set-Cookie，则更新本地存储中的 Cookie
                        if (res.data.code === 0) {
                            if (res.header['Set-Cookie']) {
                                let setCookies = res.header['Set-Cookie'].split(';');
                                setCookies = setCookies[0]
                                const cookies = wx.getStorageSync('Cookie') || {};

                                const [cookieName, cookieValue] = setCookies.split('=');
                                wx.setStorageSync('Cookie', {...cookies, [cookieName]: cookieValue});
                            }
                            wx.setStorageSync('user', res.data.data);
                            if (from) {
                                wx.navigateBack();
                                return
                            }
                            wx.switchTab({
                                url: "/pages/home/home"
                            });
                        }
                    })
                } else {
                    console.log('登录失败！' + res.errMsg)
                }
            }
        })
    }
    ,

    handleWechatLogin() {
        if (!this.data.agreed) {
            wx.showToast({
                title: '请先同意用户协议',
                icon: 'none'
            });
            return;
        }

        wx.showLoading({
            title: '登录中...'
        });

        // 获取用户信息
        wx.getUserProfile({
            desc: '用于完善用户资料',
            success: (res) => {
                const userInfo = res.userInfo;

                // 保存用户信息到全局数据和本地存储
                const app = getApp();
                app.globalData.userInfo = userInfo;
                app.globalData.isLogin = true;
                wx.setStorageSync('userInfo', userInfo);

                // 模拟登录成功
                setTimeout(() => {
                    wx.hideLoading();
                    wx.showToast({
                        title: '登录成功',
                        icon: 'success',
                        duration: 1500,
                        success: () => {
                            setTimeout(() => {
                                wx.switchTab({
                                    url: '/pages/home/home'
                                });
                            }, 1500);
                        }
                    });
                }, 1500);
            },
            fail: (err) => {
                wx.hideLoading();
                wx.showToast({
                    title: '登录失败',
                    icon: 'none'
                });
            }
        });
    }
    ,

    showAgreement() {
        wx.navigateTo({
            url: '/pages/agreement/agreement'
        });
    }
});